package cn.lg.soar.general.service.impl;

import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.common.util.current.CurrentProxy;
import cn.lg.soar.general.config.GeneralCacheKey;
import cn.lg.soar.general.entity.BizFileType;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.lg.soar.general.mapper.BizFileTypeMapper;
import cn.lg.soar.general.service.IBizFileTypeService;

import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 文件业务类型
 * @author 41225
 * @since 2024-06-02
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Service
public class BizFileTypeServiceImpl extends ServiceImpl<BizFileTypeMapper, BizFileType> implements IBizFileTypeService, CurrentProxy<BizFileTypeServiceImpl> {

    @Autowired
    protected CacheManager cacheManager;

    @CacheEvict(value = GeneralCacheKey.BIZ_FILE_TYPE, allEntries = true)
    @Override
    public boolean save(BizFileType entity) {
        return super.save(entity);
    }

    @CacheEvict(value = GeneralCacheKey.BIZ_FILE_TYPE, allEntries = true)
    @Override
    public boolean updateById(BizFileType entity) {
        return super.updateById(entity);
    }

    @CacheEvict(value = GeneralCacheKey.BIZ_FILE_TYPE, allEntries = true)
    @Override
    public boolean removeByIds(Collection<?> list) {
        return super.removeByIds(list);
    }

    @Cacheable(value = GeneralCacheKey.BIZ_FILE_TYPE, key = "'idToType'")
    public Map<Integer, String> getIdToTypeMap() {
        return list().stream().collect(Collectors.toMap(BizFileType::getId, BizFileType::getBizType));
    }

    @Cacheable(value = GeneralCacheKey.BIZ_FILE_TYPE, key = "'typeToId'")
    public Map<String, Integer> getTypeToIdMap() {
        return list().stream().collect(Collectors.toMap(BizFileType::getBizType, BizFileType::getId));
    }

    @Override
    public int typeToId(String bizType) {
        Integer id = proxy().getTypeToIdMap().get(bizType);
        if (id == null) {
            BizFileType bizFileType = new BizFileType();
            bizFileType.setBizType(bizType);
            AssertUtil.isTrue(save(bizFileType), "操作失败");
            Cache cache = cacheManager.getCache(GeneralCacheKey.BIZ_FILE_TYPE);
            if (cache != null) {
                cache.invalidate();
            }
            return bizFileType.getId();
        }
        return id;
    }

    @Override
    public String idToType(int bizTypeId) {
        return proxy().getIdToTypeMap().get(bizTypeId);
    }
}
